package com.kun.service.filter;

import cn.hutool.extra.spring.SpringUtil;
import com.kun.service.service.TokenService;
import com.kun.common.util.StringUtils;
import com.kun.domain.TUser;
import com.kun.service.util.UserContext;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
public class LoginFilter implements Filter {

    private TokenService tokenService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.tokenService = SpringUtil.getBean(TokenService.class);
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String token = httpServletRequest.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token)) {
            TUser tUser = tokenService.parseToken(token);
            UserContext.setUser(tUser);
            // 刷新令牌
            tokenService.refreshToken(tUser);
        }
        filterChain.doFilter(servletRequest, servletResponse);
        UserContext.clear();
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
